//
//  HomePageItemModel.m
//  ShowYork
//
//  Created by hxh on 2020/9/29.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "HomePageItemModel.h"

@implementation HomePageItemModel
-(id<NSObject>)diffIdentifier{
    return self;
}
-(BOOL)isEqualToDiffableObject:(id<IGListDiffable>)object{
    return [self isEqual:object];
}


+(NSDictionary *)mj_objectClassInArray{
    return @{@"contents":[HomePageContentModel class]};
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.isDisplay = @1;
        self.readyPlay = YES;
    }
    return self;
}


- (NSArray *)urls{
    NSMutableArray *arr = [NSMutableArray array];
    [_contents enumerateObjectsUsingBlock:^(HomePageContentModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [arr addObject:obj.postUrl.length == 0?@"":obj.postUrl];
    }];
    return arr;
}

- (CGFloat)imageHeight{
    CGFloat width = (kScreenW - 16 * 2 - 4 * 2)/3;
    if (_contentType.intValue == 2) {
        // 先判断有没有文字
        if (_contents.count == 1) {
            return width * 2 + 4;
        }else if (_contents.count == 2 || _contents.count == 4) {
            NSInteger row = _contents.count / 2;
            return row * width + (row - 1) * 4;
        }else{
            // 判断两行
            if (_contents.count == 5) {
                return width * 2 + 8;
            // 判断三行
            }else if (_contents.count == 7 || _contents.count == 8){
                return width * 3 + 12;
            }else{
                NSInteger row = _contents.count / 3;
                return row * width + (row - 1) * 4;
            }
        }
    }else if (_contentType.intValue == 3){
        return 225;
    }
    return 100.0f;
}
- (CGFloat)contentHeight{
    
    return 50.0f;
}

- (CGFloat)cellHeight{
    CGFloat maxH = [self heightOfLines:5 font:font(16)];
    CGSize size = [RPAppManager getTextSizeWithText:_contentText font:font(16) maxSize:CGSizeMake(kScreenW - 32, MAXFLOAT)];
    CGFloat margin = 0;
    CGFloat textH = 0;
    if (_contentText.length != 0) {
        textH = MIN(ceil(size.height),maxH);
        if (maxH > ceil(size.height)) {
            margin = 16.0f;
        }else{
            margin = 20 + 4 + 16;
        }
    }
    if (_contentType.intValue == 1){
        if (ceil(size.height) > maxH) {
            return maxH + 24.0f;
        }
        return ceil(size.height);
    }else if (_contentType.intValue == 2){
        return self.imageHeight + textH + margin;
    }else if (_contentType.intValue == 3){
        return 225 + margin + textH;
    }else{
        return (kScreenW - 48)/3*4;
    }
    return 100.0f;
}

- (CGFloat)heightOfLines:(int)lines font:(UIFont *)font{
    if (lines <= 0) {
        return 0;
    }
    NSString *str = @"*";
    for (int index = 0; index < lines - 1 ; index++) {
        str = [str stringByAppendingString:@"\n*"];
    }
    NSDictionary *dict = @{NSFontAttributeName:font};
    
    CGSize size = [str sizeWithAttributes:dict];
    
    return ceil(size.height);
}

- (NSString *)createDetailTimeStr{

    NSDate *date = [NSDate dataWithTimeSp:self.createTime.longValue];

    NSString *timeStr = [date getTimeWithFormatter:@"yyyy-MM-dd HH:mm:ss"];

    long currentDate = [NSDate date].timeIntervalSince1970 * 1000;
    
    NSDateFormatter *fmt_ = [[NSDateFormatter alloc] init];
    NSCalendar *calendar_ = [NSCalendar calendar];

    
    fmt_.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *createdAtDate = [fmt_ dateFromString:timeStr];
    
    if (createdAtDate.isThisYear) { // 今年
        if (createdAtDate.isToday) { // 今天
            NSDate *nowDate = [NSDate dataWithTimeSp:currentDate];
            NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
            NSDateComponents *cmps = [calendar_ components:unit fromDate:createdAtDate toDate:nowDate options:0];
            if (cmps.hour >= 1) { // 时间间隔 >= 1小时
                return [NSString stringWithFormat:@"%zd小时前", cmps.hour];
            }else{
                if (cmps.minute <= 0) {
                    return @"刚刚";
                }
                return [NSString stringWithFormat:@"%zd分钟前", cmps.minute];
            }
        }else {
            fmt_.dateFormat = @"M-d";
            NSString *monthDay = [fmt_ stringFromDate:createdAtDate];
            return [NSString stringWithFormat:@"%@",monthDay];
        }
    } else {
        fmt_.dateFormat = @"yyyy-M-d";
        NSString *dataStr = [fmt_ stringFromDate:createdAtDate];
        return [NSString stringWithFormat:@"%@",dataStr];
    }
}


- (NSString *)yearStr{
    
    NSDate *date = [NSDate dataWithTimeSp:self.createTime.longValue];
    NSString *timeStr = [date getTimeWithFormatter:@"yyyy年"];
    
    return timeStr;
}


- (NSArray *)contentArray{
    if (self.contentText.length != 0) {
        NSAttributedString *atts = [[NSAttributedString alloc]initWithString:self.contentText attributes:@{NSFontAttributeName:[UIFont fontWithName:@"PingFang SC" size:14]}];
        NSArray *contentArr = [self coreTextPaging:atts textFrame:CGRectMake(16, 0, kScreenW - 32, kScreenH - kNavBarHeight - 16.0 - 110 - GK_SAVEAREA_BTM)];
        return contentArr;
    }else{
        return @[];
    }
}

- (NSInteger)maxCount{
    if (self.contentType.intValue == 1) {
        return self.contentArray.count;
    }else if (self.contentType.intValue == 2){
        return self.contents.count;
    }else{
        return 0;
    }
}


- (NSArray *)coreTextPaging:(NSAttributedString *)str textFrame:(CGRect)textFrame{
    NSMutableArray *pagingResult = [NSMutableArray array];
    CFAttributedStringRef cfAttStr = (__bridge CFAttributedStringRef)str;
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(cfAttStr);
    CGPathRef path = CGPathCreateWithRect(textFrame, NULL);

    int textPos = 0;
    NSUInteger strLength = [str length];
    while (textPos < strLength)  {
        //设置路径
        CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(textPos, 0), path, NULL);
        //生成frame
        CFRange frameRange = CTFrameGetVisibleStringRange(frame);
        NSRange ra = NSMakeRange(frameRange.location, frameRange.length);

       //获取范围并转换为NSRange，然后以NSAttributedString形式保存
        [pagingResult addObject:[str attributedSubstringFromRange:ra]];
        
        //移动当前文本位置
        textPos += frameRange.length;
       
        CFRelease(frame);
    }
    CGPathRelease(path);
    CFRelease(framesetter);
    return pagingResult;
}

@end
